package org.angelica.aliyun.manager;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.BasicSessionCredentials;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.angelica.aliyun.entity.StsToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 短信服务
 * @author aizhimin
 */
public class SmsManager {

    private static final Logger logger = LoggerFactory.getLogger(SmsManager.class);

    private SmsManager(){ }
    private static SmsManager instance = new SmsManager();

    private static StsToken smsStsToken = null;
    private static IAcsClient client = null;
    public static SmsManager getInstance(StsToken stsToken){
        //token过期，则重新创建 IAcsClient
        if(smsStsToken != null && !smsStsToken.getSecurityToken().equals(stsToken.getSecurityToken())){
            if(client != null){
                client.shutdown();
            }
            client = null;
        }
        if(client == null){
            smsStsToken = stsToken;
            BasicSessionCredentials credentials = new BasicSessionCredentials(
                    stsToken.getAccessKeyId(),
                    stsToken.getAccessKeySecret(),
                    stsToken.getSecurityToken()
            );
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou");
            client = new DefaultAcsClient(profile,credentials);
        }
        return instance;
    }

    /**
     * 发送短信
     * @param phoneNumbers
     * @param signName
     * @param templateCode
     * @param templateParam
     * @return
     */
    public CommonResponse sendSms(String phoneNumbers, String signName, String templateCode, String templateParam){
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            return client.getCommonResponse(request);
        } catch (ServerException e) {
            logger.error("errCode:{},errMsg:{}",e.getErrCode(),e.getErrMsg());
        } catch (ClientException e) {
            logger.error("errCode:{},errMsg:{}",e.getErrCode(),e.getErrMsg());
        }
        return null;
    }
}
